﻿using mediaControl.ViewModels;
using mediaControl.Vo;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace mediaControl.Views
{
    /// <summary>
    /// ProgramList.xaml 的交互逻辑
    /// </summary>
    public partial class ProgramList : UserControl
    {

        public ProgramList()
        {
            InitializeComponent();
            CompositionTarget.Rendering += OnCompositionTargetRendering;
            Loaded += UserControlLoaded;
        }

        private void UserControlLoaded(object sender, RoutedEventArgs e)
        {
            if (DataContext is ProgramListViewModel viewModel)
            {
                viewModel.Music = musicPlayer;
            }
        }

        private void OnCompositionTargetRendering(object sender, EventArgs e)
        {
            double progress = musicPlayer.Position.TotalSeconds;
            process.Value = progress;
        }

        ObservableCollection<ProgramItemVo> List = new ObservableCollection<ProgramItemVo>();

        private void listView1_PreviewMouseMove(object sender, MouseEventArgs e)
        {

            if (e.LeftButton == MouseButtonState.Pressed)
            {
                var pos = e.GetPosition(listView1);  // 获取位置

                #region 源位置
                HitTestResult result = VisualTreeHelper.HitTest(listView1, pos);  //根据位置得到result
                if (result == null)
                {
                    return;    //找不到 返回
                }
                var listBoxItem = Utils.FindVisualParent<ListViewItem>(result.VisualHit);
                if (listBoxItem == null || listBoxItem.Content != listView1.SelectedItem)
                {
                    return;
                }
                #endregion

                DataObject dataObj = new DataObject(listBoxItem.Content as ProgramItemVo);
                DragDrop.DoDragDrop(listView1, dataObj, DragDropEffects.Move);  //调用方法
            }


        }


        private void listView1_Drop(object sender, DragEventArgs e)
        {
            var pos = e.GetPosition(listView1);   //获取位置
            var result = VisualTreeHelper.HitTest(listView1, pos);   //根据位置得到result
            if (result == null)
            {
                return;   //找不到 返回
            }
            #region 查找元数据
            var sourcePerson = e.Data.GetData(typeof(ProgramItemVo)) as ProgramItemVo;
            if (sourcePerson == null)
            {
                return;
            }
            #endregion

            #region  查找目标数据
            var listViewItem = Utils.FindVisualParent<ListViewItem>(result.VisualHit);
            if (listViewItem == null)
            {
                return;
            }
            var targetPerson = listViewItem.Content as ProgramItemVo;
            if (ReferenceEquals(targetPerson, sourcePerson))
            {
                return;
            }
            #endregion


            int sourceIndex = listView1.Items.IndexOf(sourcePerson);
            int targetIndex = listView1.Items.IndexOf(targetPerson);

            ObservableCollection<ProgramItemVo> voList = new ObservableCollection<ProgramItemVo>();
            ObservableCollection<ProgramItemVo> tempList = new ObservableCollection<ProgramItemVo>();
            voList = (ObservableCollection<ProgramItemVo>)listView1.ItemsSource;
            if (sourceIndex < targetIndex)  //从上面移动到下面
            {

                voList.Remove(sourcePerson);//删除源
                voList.Insert(listView1.Items.IndexOf(targetPerson) + 1, sourcePerson);


            }
            else if (sourceIndex > targetIndex)
            {
                voList.Remove(sourcePerson);//删除源
                voList.Insert(listView1.Items.IndexOf(targetPerson), sourcePerson);
            }
            //处理序号
            for (int i = 0; i < voList.Count; i++)
            {
                voList[i].No = i + 1;
                tempList.Add(voList[i]);

            }
            listView1.ItemsSource = tempList;
        }

        private static object GetDataFromListBox(ListBox source, Point point)
        {
            UIElement element = source.InputHitTest(point) as UIElement;
            if (element != null)
            {
                object data = DependencyProperty.UnsetValue;
                while (data == DependencyProperty.UnsetValue)
                {
                    data = source.ItemContainerGenerator.ItemFromContainer(element);
                    if (data == DependencyProperty.UnsetValue)
                    {
                        element = VisualTreeHelper.GetParent(element) as UIElement;
                    }
                    if (element == source)
                    {
                        return null;
                    }
                }
                if (data != DependencyProperty.UnsetValue)
                {
                    return data;
                }
            }
            return null;
        }
        private int GetCurrentIndex(GetPositionDelegate getPosition)
        {
            int index = -1;
            for (int i = 0; i < listView1.Items.Count; ++i)
            {
                ListViewItem item = GetListViewItem(i);
                if (item != null && this.IsMouseOverTarget(item, getPosition))
                {
                    index = i;
                    break;
                }
            }
            return index;
        }

        private bool IsMouseOverTarget(Visual target, GetPositionDelegate getPosition)
        {
            Rect bounds = VisualTreeHelper.GetDescendantBounds(target);
            Point mousePos = getPosition((IInputElement)target);
            return bounds.Contains(mousePos);
        }

        delegate Point GetPositionDelegate(IInputElement element);

        ListViewItem GetListViewItem(int index)
        {
            if (listView1.ItemContainerGenerator.Status != GeneratorStatus.ContainersGenerated)
                return null;
            return listView1.ItemContainerGenerator.ContainerFromIndex(index) as ListViewItem;
        }



        private void listView1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            ListView listView = sender as ListView;
            if (listView != null)
            {
                int index = -1;
                //使用SelectedIndex属性获取鼠标所在的行号
                //index = listView.SelectedIndex;
                if (index == -1)
                {
                    //如果SelectedIndex属性获取失败，则使用HitTest方法获取鼠标所在的行号
                    var hitTest = VisualTreeHelper.HitTest(listView, e.GetPosition(listView));
                    if (hitTest != null)
                    {
                        var item = VisualTreeHelper.GetParent(hitTest.VisualHit);
                        while (item != null && !(item is ListViewItem))
                        {
                            item = VisualTreeHelper.GetParent(item);
                        }
                        if (item != null)
                        {
                            ListViewItem listViewItem = item as ListViewItem;
                            listViewItem.IsSelected = true;
                            index = listView.ItemContainerGenerator.IndexFromContainer(item);
                        }
                    }
                }
                if (index >= 0 && index < listView.Items.Count)
                {
                    //选中该行
                    listView.SelectedIndex = index;
                    ListViewItem item = (ListViewItem)listView.ItemContainerGenerator.ContainerFromIndex(index);
                    item.IsSelected = true;
                    listView.SelectedItem = item;
                    // 现在item就是您通过下标获取的ListViewItem
                }
                else
                {
                    // 索引超出范围，处理错误情况
                }
            }
        }

        private void ComboBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            string flag = playFlag.Text;
            if ("True".Equals(flag))
            {
                MessageBox.Show("有节目播放中，不能修改！");
                return;
            }
            // listView1.PreviewMouseDown += voideMethod;
            //e.Handled = true;
            ComboBox comboBox = sender as ComboBox;
            ListViewItem listViewItem = Utils.FindVisualParent<ListViewItem>(comboBox);
            if (null != listViewItem)
            {
                //listViewItem.IsSelected = true;
                listView1.SelectedItem = listViewItem;

            }
        }





        private void listView1_MouseEnter(object sender, MouseEventArgs e)
        {
            ListView listView = sender as ListView;
            if (listView != null)
            {
                int index = -1;
                //使用SelectedIndex属性获取鼠标所在的行号
                //index = listView.SelectedIndex;
                if (index == -1)
                {
                    //如果SelectedIndex属性获取失败，则使用HitTest方法获取鼠标所在的行号
                    var hitTest = VisualTreeHelper.HitTest(listView, e.GetPosition(listView));
                    if (hitTest != null)
                    {
                        var item = VisualTreeHelper.GetParent(hitTest.VisualHit);
                        while (item != null && !(item is ListViewItem))
                        {
                            item = VisualTreeHelper.GetParent(item);
                        }
                        if (item != null)
                        {
                            ListViewItem listViewItem = item as ListViewItem;
                            listViewItem.IsSelected = true;
                            index = listView.ItemContainerGenerator.IndexFromContainer(item);
                        }
                    }
                }
                if (index >= 0 && index < listView.Items.Count)
                {
                    //选中该行
                    listView.SelectedIndex = index;
                    ListViewItem item = (ListViewItem)listView.ItemContainerGenerator.ContainerFromIndex(index);
                    item.IsSelected = true;
                    listView.SelectedItem = item;
                    // 现在item就是您通过下标获取的ListViewItem
                }
                else
                {
                    // 索引超出范围，处理错误情况
                }
            }
        }

        private void process_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (musicPlayer.Source != null && isdragging)
            {
                musicPlayer.Position = TimeSpan.FromSeconds(process.Value);
            }
        }

        private void CheckBox_Click(object sender, RoutedEventArgs e)
        {
            CheckBox checkBox = sender as CheckBox;
            if (musicPlayer.Source != null)
            {
                if ((bool)checkBox.IsChecked)
                {
                    vloue.IsEnabled = true;
                }
                else
                {
                    vloue.IsEnabled = false;
                }
            }
        }

        private void vloue_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (musicPlayer.Source != null)
            {
                musicPlayer.Volume = e.NewValue;
            }
        }
        private bool isdragging = false;

        private void Grid_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Space)
            {
                // 在这里处理空格键按下的逻辑
                MessageBox.Show("空格键被按下了！");
            }
        }

        private void process_DragCompleted(object sender, DragCompletedEventArgs e)
        {
            isdragging = false;
        }

        private void process_DragStarted(object sender, DragStartedEventArgs e)
        {
            isdragging = true;
        }

        private void listView1_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {


            if (e.RightButton == MouseButtonState.Pressed)
            {
                listView1.AddHandler(ContextMenu.ContextMenuOpeningEvent, new ContextMenuEventHandler(ListViewContextMenu_Opening), true);

                return;
            }

        }
        private void ListViewContextMenu_Opening(object sender, ContextMenuEventArgs e)
        {
            string flag = playFlag.Text;
            if ("True".Equals(flag))
            {
                e.Handled = true;
            }
            else
            {
                e.Handled = false;
            }
        }

        private void listView1_MouseDown(object sender, MouseButtonEventArgs e)
        {
            var listView = sender as ListView;
            if (listView != null)
            {
                var index = listView.Items.Count - 1;
                if (index >= 0)
                {
                    listView.SelectedIndex = index;
                    listView.ScrollIntoView(listView.Items[index]);
                }
            }
        }
    }
    internal static class Utils
    {
        //根据子元素查找父元素
        public static T FindVisualParent<T>(DependencyObject obj) where T : class
        {
            while (obj != null)
            {
                if (obj is T)
                    return obj as T;

                obj = VisualTreeHelper.GetParent(obj);
            }
            return null;
        }
    }
}
